﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using EFCoreRepository.DbContexts;
using Zoomtel.Entity.BIZ;
using Zoomtel.Persist.BIZ;
using Zoomtel.Persist.BIZ.Models;

namespace Zoomtel.Service.BIZ
{
    public class ProfitService
    {
        private ProfitRepository _profitRepository;
        private ItemPromotionRepository _itemPromotionRepository;
        private AgentInfoRepository _agentInfoRepository;
        private AgentInfoService _agentInfoService;
        private DefaultDbContext _defaultDbContext;
        private ChangeBalanceRepository _changeBalanceRepository;
        public ProfitService(DefaultDbContext defaultDbContext, AgentInfoService agentInfoService, ChangeBalanceRepository changeBalanceRepository,ProfitRepository profitRepository, ItemPromotionRepository itemPromotionRepository, AgentInfoRepository agentInfoRepository)
        {
            _changeBalanceRepository = changeBalanceRepository;
             _defaultDbContext = defaultDbContext;
            _profitRepository = profitRepository;
            _itemPromotionRepository = itemPromotionRepository;
            _agentInfoRepository = agentInfoRepository;
            _agentInfoService = agentInfoService;
        }

        //public async Task<IResultModel> CalcAndQueryResult(ItemPromotionQueryModel model)
        //{
        //    string batchcode = _itemPromotionRepository.GetSeq("S_BIZ_BATCH").ToString();
        //    model.Batch = batchcode;
        //    int count = await CalcAndInserProfitAsync(model);
        //    if (count > 0)
        //    {
        //        ProfitQueryMode profitQueryMode = new ProfitQueryMode();
        //        profitQueryMode.Batch = batchcode;
        //        profitQueryMode.ItemId = model.ItemId;
        //        var result = QueryCalcResult(profitQueryMode);
        //        return ResultModel.Success(result);
        //    }

        //    return ResultModel.Failed("没有查询到分销数据！");
        //}

        public async Task<IResultModel> QueryCalcResult(ProfitQueryMode model)
        {
            
            var result = await _profitRepository.QueryCalcResult(model);

            return ResultModel.Success(result);
        }

        public async Task<IResultModel> CalcAndInserProfitAsync(ItemPromotionQueryModel model)
        {
            string batchcode = _itemPromotionRepository.GetSeq("S_BIZ_BATCH").ToString();
            model.Batch = batchcode;

            _profitRepository.BeginTrans();
            //标记批次,只计算该批次的收益
            int count = await _itemPromotionRepository.UpdateBatchAsync(model);

            //参与该产品分销的分销商列表
            List<ItemPromotionModel> agentList = _itemPromotionRepository.QueryAgent(model);

            model.ClickType = "10";//第一段,表示访问了产品
            List<ItemPromotionModel> visitInfoList = _itemPromotionRepository.QueryAgentCount(model);

            model.ClickType = "20";//第二段,表示看完了广告
            List<ItemPromotionModel> finishInfoList = _itemPromotionRepository.QueryAgentCount(model);

            int totalFinishCount = 0;
            //累加完成总数
            foreach (ItemPromotionModel finish in finishInfoList)
            {
                totalFinishCount = totalFinishCount + finish.VisitCount;//累加完成数量
            }
            
            try
            {
                //计算平均收益
                decimal perProfit = (model.TotalAmount / totalFinishCount).ToString("#0.00").ToDecimal();
                ProfitEntity profitEntity = null;
                foreach (ItemPromotionModel item in agentList)
                {
                    profitEntity = new ProfitEntity();
                    profitEntity.Id = _profitRepository.GetSeq("S_BIZ_PROFIT").ToString();
                    profitEntity.AgentId = item.AgentId;
                    profitEntity.ItemId = item.ItemId;
                    profitEntity.ProfitDate = DateTime.Today;
                    profitEntity.ProfitType = "10";//激励视频
                    profitEntity.CreateTime = DateTime.Now;
                    profitEntity.ADTotalAmount = model.TotalAmount;
                    profitEntity.AuditFlag = "10";
                    profitEntity.Batch = model.Batch;
                    profitEntity.Profit = 0;//收益先默认为0,计算完成后再赋值

                    profitEntity.VisitCount = 0;
                    profitEntity.TestCount = 0;
                    profitEntity.FinishCount = 0;

                    foreach (ItemPromotionModel visit in visitInfoList)
                    {
                        if (visit.ItemId == item.ItemId && visit.AgentId == item.AgentId)
                        {
                            profitEntity.VisitCount = visit.VisitCount;
                            profitEntity.TestCount = visit.VisitCount;
                            break;
                        }
                    }

                    foreach (ItemPromotionModel finish in finishInfoList)
                    {
                        if (finish.ItemId == item.ItemId && finish.AgentId == item.AgentId)
                        {
                            profitEntity.FinishCount = finish.VisitCount;
                            //finishInfoList.Remove(finish);
                            //totalFinishCount = totalFinishCount+ finish.VisitCount;//累加完成数量
                            profitEntity.Profit = finish.VisitCount * perProfit;
                            break;
                        }
                    }
                    _profitRepository.Insert(profitEntity);
                }
                //计算评价收益并更新每个分销商的收益
                //if (totalFinishCount>0) {
                //    decimal profit = (model.TotalAmount / totalFinishCount).ToString("#0.00").ToDecimal();
                //    profitEntity = new ProfitEntity();
                //    profitEntity.ItemId = model.ItemId;
                //    profitEntity.Batch = model.Batch;
                //    profitEntity.Profit = profit;
                //    count= await _profitRepository.UpdateProfitAsync(profitEntity);
                //}

                //根据收益更余额变更表并更新分销商余额
                var result = _profitRepository.FindList(a => a.Batch == model.Batch && a.ItemId == model.ItemId);
                //ChangeBalanceEntity changeBalanceEntity = null;
                foreach (ProfitEntity item in result)
                {
                    await _agentInfoService.ChangeBalance(item.AgentId, ChangeType.Separate.ToString(), item.Profit, item.Id, "分销收益", _defaultDbContext.LoginInfo.LoginName);

                    //changeBalanceEntity = new ChangeBalanceEntity();
                    //var agentInfoEntity = _agentInfoRepository.QueryEntity(item.AgentId);

                    //changeBalanceEntity.Id= _profitRepository.GetSeq("S_BIZ_CHANGEBALANCE").ToString();
                    //changeBalanceEntity.AgentId = item.AgentId;
                    //changeBalanceEntity.Type = "10";//10 收益  2-提现  30手动修改
                    //changeBalanceEntity.Amount = item.Profit;

                    //changeBalanceEntity.Balance = agentInfoEntity.AccountBalance + item.Profit;
                    //changeBalanceEntity.Remarks = item.Id;
                    //changeBalanceEntity.CreatedTime = DateTime.Now;
                    //changeBalanceEntity.Creator = _defaultDbContext.LoginInfo.LoginName;

                    ////插入变更表记录
                    //_changeBalanceRepository.Insert(changeBalanceEntity);

                    ////更新余额
                    //agentInfoEntity.AccountBalance = changeBalanceEntity.Balance;
                    //_agentInfoRepository.Update(agentInfoEntity);
                }

                _profitRepository.Commit();

                return ResultModel.Success(batchcode);
            }
            catch (Exception e)
            {
                return ResultModel.Failed(e.Message);
            }
            finally {
                _profitRepository.Rollback();
            }
            return ResultModel.Failed();
        }
        

        public async Task<IResultModel> CheckIsSettle(ProfitQueryMode model)
        {
            bool flag=_profitRepository.Exists(a => a.Batch == model.Batch && a.ItemId == model.ItemId && a.AuditFlag == model.AuditFlag);
            if (flag) {
                return ResultModel.Failed("当前产品已经做了收益结算！");
            }
            return ResultModel.Success();

        }

        public async Task<IResultModel> CalcResultRollBack(ProfitQueryMode model)
        {
            var result = new ResultModel<string>();

            var profits = _profitRepository.FindList(a => a.Batch == model.Batch&&a.ItemId==model.ItemId);

            try
            {
                _profitRepository.BeginTrans();
                //ChangeBalanceEntity changeBalanceEntity = null;
                foreach (var profit in profits)
                {
                    string pid = profit.Id;
                    _profitRepository.Delete(pid);//删除收益记录

                    await _agentInfoService.ChangeBalance(profit.AgentId, ChangeType.CalcRollBack.ToString(), profit.Profit*-1, profit.Id, "分销结果撤回", _defaultDbContext.LoginInfo.LoginName);
                    //添加余额变更记录
                    //changeBalanceEntity = new ChangeBalanceEntity();
                    //var agentInfoEntity = _agentInfoRepository.QueryEntity(profit.AgentId);

                    //changeBalanceEntity.Id = _profitRepository.GetSeq("S_BIZ_CHANGEBALANCE").ToString();
                    //changeBalanceEntity.AgentId = profit.AgentId;
                    //changeBalanceEntity.Type = "40";//10 收益  20提现  30手动修改  40计算撤回
                    //changeBalanceEntity.Amount = profit.Profit;

                    //changeBalanceEntity.Balance = agentInfoEntity.AccountBalance - profit.Profit;
                    //changeBalanceEntity.Remarks = profit.Id;
                    //changeBalanceEntity.CreatedTime = DateTime.Now;
                    //changeBalanceEntity.Creator = _defaultDbContext.LoginInfo.LoginName;

                    ////插入变更表记录
                    //await _changeBalanceRepository.InsertAsync(changeBalanceEntity);

                    ////更新余额
                    //agentInfoEntity.AccountBalance = changeBalanceEntity.Balance;
                    //await _agentInfoRepository.UpdateAsync(agentInfoEntity);
                    
                }

                //回滚激励视频推广记录
                ItemPromotionQueryModel itemPromotionQueryModel = new ItemPromotionQueryModel();
                itemPromotionQueryModel.Batch = model.Batch;
                itemPromotionQueryModel.ItemId = model.ItemId;
                int count = await _itemPromotionRepository.RollBackPromotions(itemPromotionQueryModel);

                _profitRepository.Commit();
                return ResultModel.Success(count);
            }
            catch (Exception e) {
                return ResultModel.Failed(e.Message);
            }
            finally
            {
                _profitRepository.Rollback();
            }
            return ResultModel.Failed();
        }


    }
}
